package com.wfcm.utils;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Auther: liu
 * @Date: 2018/7/9 15:12
 * @Description: 登陆工具类
 */
@Service
public class ISsoStudyHelper {

    private static final Logger logger = LoggerFactory.getLogger(ISsoStudyHelper.class);

    private static final String STUDY_USER_KEY_ = "STUDY_USER_KEY_";
    //private static final String LOGIN_TOKEN_KEY_ = "LOGIN_TOKEN_KEY_";

    private static JedisPool myJedisPool;

    @Autowired
    private JedisPool jedisPool;

    @PostConstruct
    public void init() {
        myJedisPool = jedisPool;
    }

    /**
     * 保存用户登陆信息
     *
     * @param userid
     * @return
     */
    public static String login(Integer userid) {
        Jedis jedis = myJedisPool.getResource();
        Map<Integer, String> map = new HashMap();
        String token = UUID.randomUUID().toString();
        try {
            jedis.hset(STUDY_USER_KEY_ + userid, "date", (System.currentTimeMillis() / 1000) + "");
            jedis.hset(STUDY_USER_KEY_ + userid, "time", (System.currentTimeMillis() / 1000) + "");
           // jedis.set(LOGIN_TOKEN_KEY_ + token, userid + "");
            Set<String> keys = jedis.hkeys(STUDY_USER_KEY_ + userid);
            if (keys.size() == 4) {
                for (String key : keys) {
                    map.put(Integer.valueOf(jedis.hget(STUDY_USER_KEY_ + userid, key)), key);
                }
                String delKey = map.get(Collections.min(map.keySet()));
                jedis.hdel(STUDY_USER_KEY_ + userid, delKey);
                jedis.del(STUDY_USER_KEY_ + delKey);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        } finally {
            jedis.close();
        }
        return token;
    }


}
